from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session

from controller.PermissionAdminController import PermissionAdminController
from controller.PublicAdminController import PublicAdminController
from schema.ParamSchema import PortMenusInfo
from util.Auth import check_token
from util.DataBaseTools import get_db_session
from util.ErrorCode import ErrorCode
from util.LogHelper import Log

permission_admin_router = APIRouter()

@permission_admin_router.post("/permission/getmenus/port", summary='根据岗位获取菜单权限')
def get_menus_by_port(port_id: int, db: Session = Depends(get_db_session), result=Depends(check_token)):
    Log.getlogger().debug(f'recieved request:/permission/getmenus/port')
    if result.get('code') == 0:
        if result.get('data').port_id == 0:
            if PublicAdminController.has_permission(result.get('data').port_id, '/permission/query', db):
                response = PermissionAdminController.get_menus(port_id, db)
                return response
            else:
                return {'code': ErrorCode.USERID_HAS_NO_PERMISSION.value, 'message': 'user has no permission'}
        else:
            return {'code': ErrorCode.USERID_HAS_NO_PERMISSION.value, 'message': 'user has no permission'}
    else:
        return result


@permission_admin_router.post("/permission/getmenus", summary='获取登录用户岗位菜单权限')
def get_menus(db: Session = Depends(get_db_session), result=Depends(check_token)):
    Log.getlogger().debug(f'recieved request:/permission/getmenus')
    if result.get('code') == 0:
        port_id = result.get('data').port_id
        response = PermissionAdminController.get_menus(port_id, db)
        return response
    else:
        return result


@permission_admin_router.post("/permission/setmenus", summary='设置岗位菜单权限')
def set_menus(portMenusInfo: PortMenusInfo, db: Session = Depends(get_db_session), result=Depends(check_token)):
    Log.getlogger().debug(f'recieved request:/permission/setmenus')
    if result.get('code') == 0:
        if result.get('data').port_id == 0:
            if PublicAdminController.has_permission(result.get('data').port_id, '/permission/mod', db):
                response = PermissionAdminController.set_menus(portMenusInfo, db)
                return response
            else:
                return {'code': ErrorCode.USERID_HAS_NO_PERMISSION.value, 'message': 'user has no permission'}
        else:
            return {'code': ErrorCode.USERID_HAS_NO_PERMISSION.value, 'message': 'user has no permission'}
    else:
        return result